// ==UserScript==
// @name         CSU AutoPlay Assistant
// @tag          Tool
// @namespace    https://dlmirror.ren
// @version      2025-04-29
// @description  Auto learn CSU class
// @author       未入伏_ShiWu
// @match        https://cws.edu-edu.com/page/client
// @icon         https://v2.cn.vuejs.org/images/logo.svg
// @updateURL    https://gitee.com/InfinityEx/csu-autoplay-assistant/raw/master/CSU%20AutoPlay%20Assistant.js
// @downloadURL  https://gitee.com/InfinityEx/csu-autoplay-assistant/raw/master/CSU%20AutoPlay%20Assistant.js
// @grant        GM_setValue
// @grant        GM_getValue

// ==/UserScript==
let noRepeat=0;

if (GM_getValue("grantNotify")==undefined){
  console.log(GM_getValue("grantNotify"))
  sendNotification(
      "已启用弹窗",
      "弹窗启用成功，课程连播完毕后请关注右下角弹窗提醒手动切课",
      "https://cws.edu-edu.com/static/img/favicon.ico"
  );
}

function sendNotification(title, body, icon, callback) {
  // 先检查浏览器是否支持
  if (!("Notification" in window)) {
    // IE浏览器不支持发送Notification通知!
    return;
  }
  if (Notification.permission === "denied") {
    // 如果用户已拒绝显示通知
    return;
  }
  if (Notification.permission === "granted") {
    //用户已授权，直接发送通知
    notify();
  } else {
    // 默认，先向用户询问是否允许显示通知
    Notification.requestPermission(function (permission) {
      // 如果用户同意，就可以直接发送通知
      if (permission === "granted") {
        notify();
      }
    });
  }

  function notify() {
    let notification = new Notification(title, {
      icon: icon,
      body: body,
      requireInteraction: true, //始终显示通知
    });
    notification.onclick = function () {
      //callback && callback();
      console.log("单击通知框");
      grantCheck();
    };
    notification.onclose = function () {
      console.log("关闭通知框");
      grantCheck();
    };
  }
}

// 预留
function warnNotify(title,icon,body,diff) {
  let notification = new Notification(title, {
    icon: icon,
    body: body,
    requireInteraction: true, //始终显示通知
  });
  if(diff==1){
    noRepeat=1
  }
  notification.onclick = function () {
    //callback && callback();
    console.log("单击通知框");
    noRepeat=0;
  };
  notification.onclose = function () {
    console.log("关闭通知框");
    noRepeat=0;
  };
}


function runCheck(){
    // Call FaceCheck
    faceCheck();
    // Call CalcVerify
    CalcVerify();

    // Select aliplayer Elements
    //var ali=document.querySelector('#J_prismPlayer > video');
    var ali=document.getElementById("J_prismPlayer");
    // Get aliplayer status
    let ali_status=ali.children.item(0).player.getStatus();
    if (ali_status=="loading" || ali_status=="pause"){
        //console.log("???");
        //ali.firstChild.play();
        //ali.children.item(0).play();
        var saver=document.getElementsByClassName("prism-big-play-btn")
        saver.item(0).click();
    }
    console.log(ali_status);
    var list=document.getElementsByClassName("render-content__video");
    var vRatio=document.getElementsByClassName("videoRatio");
    var activeVideo=-1;
    console.log("length:"+list.length)
    for(var k=0;k<list.length;k++){
        // get active number
        if(list.item(k).className=="render-content__video activeVideo"){
            activeVideo=k;
            //console.log("active order: "+activeVideo);
            //console.log(vRatio.item(activeVideo).innerHTML)
            if(vRatio.item(activeVideo).innerHTML=="/ 已学100%"){
                if(activeVideo!=-1 && activeVideo==(list.length)-1){
                    sendNotification(
                        "课程已学习完毕",
                        "有课程已经学习完毕了，请手动换课",
                        "https://cws.edu-edu.com/static/img/favicon.ico"
                    );
                    console.log("小节已学完")
                    ali.firstChild.pause();
                    ali.children.item(0).pause();
                    console.log("当前课程已学完 "+(activeVideo+1)+" / "+list.length+"小节")
                    clearInterval(loopRun)
                }else if(activeVideo!=-1 && activeVideo<(list.length)-1){
                    continueCheck();
                    list.item(activeVideo+1).click();
                }
            }
        }
    }
    console.log("当前正在学习："+document.getElementsByClassName("activeVideo").item(0).title+"  "+Math.round(ali.children.item(0).player.getCurrentTime())+"/"+Math.round(ali.children.item(0).player.getDuration()))
    //console.log("学习进度："+ali.children.item(0).player.getCurrentTime()+"/"+ali.children.item(0).player.getDuration())
    console.log("当前课程进度 "+(activeVideo+1)+" / "+list.length+"小节")
};

function grantCheck(){
  if (GM_getValue("grantNotify")==undefined){
      GM_setValue("grantNotify","zjpx.csu.edu.cn")
      GM_setValue("grantOvertime",1751212800000)
  }
  else{
      console.log(GM_getValue("grantNotify"));
      console.log(GM_getValue("grantOvertime"));
  }
}

function CalcVerify(){
  // 确认遮罩状态
  var modalMask=document.getElementsByClassName("ivu-modal-mask");
  console.log("modalMask: "+modalMask.item(0))
  // ClassName获取
  var header=document.getElementsByClassName("ivu-modal-header-inner");
  // 选项ClassName获取
  var wrapper=document.getElementsByClassName("ivu-radio-wrapper ivu-radio-group-item ivu-radio-default")
  // 选项长度获取(避免出现不定选项)
  var wrapperLen=wrapper.length;
  // 初始化正确选项序号
  var rightAnwser=-1;
  // 提交答案按钮
  var submitAS=document.getElementsByClassName("ivu-btn ivu-btn-default")
  // 状态判别
  var maskStatus=modalMask.item(0).getAttribute("style")
  console.log("maskStatus: "+maskStatus)
  // 判断遮罩是否不再隐藏，并对算术题进行作答
  if(maskStatus.indexOf("display: none;")==-1){
      if(header.item(0).innerHTML="学习过程确认"){
          var question=document.getElementsByClassName("questionBox").item(0).innerHTML;
          if(question.indexOf(" = ?")!=-1){
            question=eval(question.replace(" = ?",""));
            console.log(question);
            for(var as=0;as<wrapperLen;as++){
                if(eval(wrapper.item(as).textContent==question)){
                    rightAnwser=as;
                }
            }
          }
          console.log("rightAnwser is: "+rightAnwser)
          wrapper.item(rightAnwser).click();
          console.log("clicked:rightAnwser")
          timedelay(3000)
          setTimeout(null,3000)
          submitAS.item(0).click();
          console.log("clicked:submit")
      }
  }
}

function continueCheck(){
  // 确认遮罩状态
  var modalMask=document.getElementsByClassName("ivu-modal-mask");
  // ClassName获取
  var ensureBox=document.getElementsByClassName("ivu-modal").item(5).getAttribute("style");
  var ensureBtn=document.getElementsByClassName("ivu-btn-default");
  // 状态判别
  var maskStatus=modalMask.item(0).getAttribute("style");
  // 判断遮罩是否不再隐藏，并对算术题进行作答
  if(maskStatus.indexOf("display: none;")==-1){
    // 判断提醒是否显示
    if(ensureBox.indexOf("display: none;")==-1){
      if(ensureBtn.item(2).innerHTML.indexOf("取消")==-1){
        ensureBtn.item(2).click();
      }
    }
  }
}

function faceCheck(){
  // 确认遮罩状态
  var modalMask=document.getElementsByClassName("ivu-modal-mask");
  // ClassName获取
  var fcBox=document.getElementsByClassName("ivu-modal").item(1).getAttribute("style");
  // 状态判别
  var maskStatus=modalMask.item(0).getAttribute("style");
  if(maskStatus.indexOf("display: none;")==-1){
    if(fcBox.indexOf("display: none;")==-1){
      warnNotify(
        "人脸识别",
        "有课程出发人脸识别，请尽快完成人脸验证",
        "https://cws.edu-edu.com/static/img/favicon.ico"
      );
    }
  }
}

function wait(delay) {
    return new Promise(resolve => setTimeout(resolve, delay));
}

async function timedelay(time) {
    await wait(time); // 等待2秒
}

let loopRun=setInterval(()=>{
  if(noRepeat==0){
    runCheck();
  }
},5000)



// API

// Play controller
// ali.play();
// ali.pause();

// Status API
// ali.player.getCurrentTime();
// ali.player.getDuration();
// ali.player.getStatus();